﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Security.Cryptography;
using System.ComponentModel;

namespace TARADesktopPatient
{
	public partial class LoginPage
	{
        tara_wcf.ItaraServiceClient svc = new tara_wcf.ItaraServiceClient();
        public tara_wcf.patient patient = new tara_wcf.patient();

		public LoginPage()
		{
			this.InitializeComponent();
            tbxUsername.Text = "S9204433E";
            pbxPassword.Password = "test";
            tbxUsername.Focus();
			// Insert code required on object creation below this point.
		}

        int uid;
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            uid = Login(tbxUsername.Text, Hash(pbxPassword.Password));
            if (uid != 0)
            {
                //set up backgroundworker
                BackgroundWorker bgWorker = new BackgroundWorker();
                bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
                bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
                bgWorker.WorkerSupportsCancellation = true;

                //run background worker
                bgWorker.RunWorkerAsync(500);
            }
            else
            {
                MessageBox.Show("Wrong Username or Password");//Login Failed
            }
        }

        void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            svc.retrievePatientCompleted += new EventHandler<tara_wcf.retrievePatientCompletedEventArgs>(svc_retrievePatientCompleted);
            svc.retrievePatientAsync(uid);
        }

        void svc_retrievePatientCompleted(object sender, tara_wcf.retrievePatientCompletedEventArgs e)
        {
            if (e.Error == null && e.Result != null)
            {
                patient = e.Result;
                try
                {
                    NavigationService.Navigate(new MainPage(patient));
                }
                catch (NullReferenceException ex)
                {

                }
            }
        }

        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //throw new NotImplementedException();

            //Dispatcher.BeginInvoke((Action) =>
            //{

            //});
        }

        private void tbxUsername_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                uid = Login(tbxUsername.Text, Hash(pbxPassword.Password));
                if (uid != 0)
                {
                    //set up backgroundworker
                    BackgroundWorker bgWorker = new BackgroundWorker();
                    bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
                    bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
                    bgWorker.WorkerSupportsCancellation = true;

                    //run background worker
                    bgWorker.RunWorkerAsync(500);
                }
                else
                {
                    if (noConnection == false)
                    {
                        MessageBox.Show("Wrong Username or Password");//Login Failed
                    }
                }
            }
        }

        private void pbxPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                uid = Login(tbxUsername.Text, Hash(pbxPassword.Password));
                if (uid != 0)
                {
                    //set up backgroundworker
                    BackgroundWorker bgWorker = new BackgroundWorker();
                    bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
                    bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
                    bgWorker.WorkerSupportsCancellation = true;

                    //run background worker
                    bgWorker.RunWorkerAsync(500);
                }
                else
                {
                    if (noConnection == false)
                    {
                        MessageBox.Show("Wrong Username or Password");//Login Failed
                    }
                }
            }
        }

        #region Local Login Methods
        private string Hash(string ToHash)
        {
            // First we need to convert the string into bytes, which means using a text encoder.
            Encoder enc = System.Text.Encoding.ASCII.GetEncoder();

            // Create a buffer large enough to hold the string
            byte[] data = new byte[ToHash.Length];
            enc.GetBytes(ToHash.ToCharArray(), 0, ToHash.Length, data, 0, true);

            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] result = sha1.ComputeHash(data);

            return BitConverter.ToString(result).Replace("-", "");
        }

        bool noConnection = false;
        private int Login(string username, string password)
        {
            string Key, ToHash;
            try
            {
                string Token = svc.GetToken();
                ToHash = username + "|" + password + "|" + Token;
                Key = Hash(ToHash) + "|" + username + "|I would like to log this string in a DB";

                return svc.PatientUseService(Key);
            }
            catch (Exception ex)
            {
                noConnection = true;
                MessageBox.Show("Kindly Check Connection");
            }
            return 0;
        }
        #endregion
	}
}